package com.ruoyi.framework.security.handle;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.ServletUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 
 * @author ruoyi
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    @Serial
    private static final long serialVersionUID = -8970718410437077606L;

    @Value("${spring.security.oauth2.client.registration.keycloak.provider}")
    private String registration;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        boolean isAjax = ServletUtils.isAjaxRequest(request);
        // 判断如果是 Ajax 访问则返回 401 状态，否则就重定向到单点登录页面
        if(isAjax){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            String json = "{\"code\": " + HttpStatus.UNAUTHORIZED + ", \"msg\": \"Unauthorized\"}";
            response.getWriter().write(json);
        }else{
            String defaultAuthorizationRequestBaseUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
            new LoginUrlAuthenticationEntryPoint(defaultAuthorizationRequestBaseUri + "/" + registration)
                    .commence(request, response, e);
        }
    }
}
